package cn.lijiajia3515.cairo.security.web.authentication;

import cn.lijiajia3515.cairo.core.business.DefaultBusiness;
import cn.lijiajia3515.cairo.core.result.BusinessResult;
import cn.lijiajia3515.cairo.http.converter.AbstractHttpMessageHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.web.accept.ContentNegotiationManager;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 认证成功处理器
 * <p>异常message 输出到 response</p>
 */
@Slf4j
public class CairoHttpMessageAuthenticationSuccessHandler extends AbstractHttpMessageHandler implements AuthenticationSuccessHandler {

	public CairoHttpMessageAuthenticationSuccessHandler(List<HttpMessageConverter<?>> converters) {
		super(converters, null);
	}

	public CairoHttpMessageAuthenticationSuccessHandler(List<HttpMessageConverter<?>> converters, ContentNegotiationManager manager) {
		super(converters, manager);
	}

	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
		writeWithMessageConverters(BusinessResult.builder().business(DefaultBusiness.Success).data(authentication).build(), new ServletServerHttpRequest(request), new ServletServerHttpResponse(response));
	}
}
